<template>
  <q-btn class="btn margin-r-10" outline color="primary" :label="label" v-if="permission === null">
    <input ref="uploadInput" type="file" @input="importFile($event)" multiple class="q-uploader__input overflow-hidden absolute-full"
           accept="application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet">
  </q-btn>
  <q-btn class="btn margin-r-10" outline color="primary" :label="label" v-else v-has="{id: permission}">
    <input ref="uploadInput" type="file" @input="importFile($event)" multiple class="q-uploader__input overflow-hidden absolute-full"
           accept="application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet">
  </q-btn>
</template>

<script>
import { uploadFlie } from 'src/boot/template/template-upload'
import { mapGetters } from 'vuex'
import _ from 'lodash'
export default {
  name: 'upload-btn',
  props: {
    label: {
      type: String,
      default: '批量导入'
    },
    errTips: {
      default: null
    },
    url: Function,
    permission: {
      default: null
    },
    query: {
      default: {}
    }
  },
  computed: {
    ...mapGetters([
      'client'
    ])
  },
  data () {
    return {
      fileName: null // 文件名（用于订阅）
    }
  },
  methods: {
    // 批量导入上传文件
    importFile (event) {
      try {
        if (!this.$utils.fileTypeHoldUp(event.target.files[0].name, ['.xls', '.xlsx'])) {
          return
        }
        this.$q.loading.show()
        // let res = await this.$uploadPriviateFile(event.target.files, this.CommonConfig.ossFilePath.excelDir)
        const res = this.$getUploadPath(event.target.files, this.CommonConfig.ossFilePath.excelDir)
        this.fileName = res.fileNameNew
        this.onSubscribe()
        uploadFlie(res.uploadPath, event.target.files[0], res.fileNameNew).then(res => {
          if (res.code !== '1200') {
            this.$showErrTips('上传失败，请稍后重试')
            this.closeUbscribeTopic()
            this.$refs.uploadInput.value = null
          }
        }).catch(res => {
          console.log(res)
          this.closeUbscribeTopic()
          this.$refs.uploadInput.value = null
        })
      } catch (e) {
        this.$q.loading.hide()
        this.$refs.uploadInput.value = null
      }
    },
    onSubscribe () {
      if (this.client) {
        this.client.subscribe(
          `${this.CommonConfig.socketConfig.SOCKET_TOPIC.uploadFile.subscribeTopic}${this.fileName}`, this.onMessageArrived, { id: `${this.fileName}` }
        )
      } else {
        setTimeout(() => {
          this.onSubscribe()
        }, 200)
      }
    },
    closeUbscribeTopic () {
      this.client.unsubscribe(`${this.fileName}`)
      this.$q.loading.hide()
    },
    onMessageArrived (message) {
      let msg = JSON.parse(message.body).data
      if (msg.requestId !== this.fileName) {
        return
      }
      if (msg.code + '' !== '200') {
        this.$showErrTips('上传失败，请稍后重试')
        this.closeUbscribeTopic()
        return
      }
      let query = _.cloneDeep(this.query)
      console.log(query, '111')
      if (this.url) {
        query.url = msg.data
        this.url(query).then(res => {
          this.closeUbscribeTopic()
          let message = '<div style="overflow-y: auto;max-height: 50vh" class="scrollbar">'
          message += this.errTips ? this.errTips(res) : this.defaultErrTips(res)
          message += '</div>'

          // console.log(this.errTips, message, 'miaomiaomiao')
          this.$q.dialog({
            title: `<p class="dialog-notice-title"><i class="iconfont icontubiao-28"></i>
          提示</p>`,
            html: true,
            message: message,
            ok: {
              unelevated: true,
              label: '确认'
            }
          })
          this.$emit('refresh')
        }).catch(res => {
          console.log(res)
          this.closeUbscribeTopic()
        })
      } else {
        this.$emit('uploadUrlSuccess', msg.data)
      }
      this.$refs.uploadInput.value = null
    },
    defaultErrTips (res) {
      let newMsg = ''
      if (JSON.stringify(res.data.causeMap) !== '{}') {
        let msgArr = []
        for (let i in res.data.causeMap) {
          msgArr.push({ [i]: res.data.causeMap[i] })
        }
        msgArr.forEach(o => {
          newMsg = newMsg + `第${Object.keys(o)}行导入失败，原因:${Object.values(o)}<br/>`
        })
      } else {
        newMsg = '失败0条'
      }
      let message = ''
      message = `操作成功${res.data.successNum}条<br/>${newMsg}`
      return message
    }
  }
}
</script>

<style scoped lang="stylus">

</style>
